package com.health.memberbackstage.filters;

import com.alibaba.fastjson.JSON;
import com.health.memberbackstage.mapper.MemberMapper;
import com.health.memberbackstage.pojo.Member;
import com.health.memberbackstage.pojo.R.Result;
import com.health.memberbackstage.pojo.R.ResultEnum;
import com.health.memberbackstage.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class LoginInterceptor extends UsernamePasswordAuthenticationFilter {

    @Autowired
    private MemberMapper memberMapper;

    public LoginInterceptor(AuthenticationManager authenticationManager){
        setAuthenticationManager(authenticationManager);
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        User user = (User) authResult.getPrincipal();
        String memberID = user.getUsername();

        Map map = new HashMap();
        map.put("username",user.getUsername());

        String jwt = JwtUtils.createToken(map, memberID);

        Result r = Result.success(jwt);
        response.getWriter().write(JSON.toJSONString(r));
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {

        response.setContentType("application/json;charset=utf-8");
        Result r = Result.fail(ResultEnum.NO_USER);
        response.getWriter().write(JSON.toJSONString(r));
    }
}
